/**
 * 
 */
package com.tc.dispatch.web.schedule.dispatch;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.csservice.model.Product;
import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsalgorithm.spec.spec;
import com.tc.dispatch.gsservice.basic.common.regulation;
import com.tc.dispatch.gsservice.basic.common.tcdate;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.GSConstants;
import com.tc.dispatch.gsservice.model.SsignDensity;
import com.tc.dispatch.rwservice.ejb.RWServiceLocal;
import com.tc.dispatch.rwservice.exception.RWException;
import com.tc.dispatch.rwservice.model.ERPPlanCtrl;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.rwservice.rwHelper;
import com.tc.dispatch.web.util.DateJsonValueProcessor;
import com.tc.dispatch.web.util.FloatJsonValueProcessor;
import com.tc.dispatch.web.util.tools;

/**
 * @author cajeep
 * 
 */
public class TaskDispatchIndex extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public TaskDispatchIndex() {
		super();
	}

	public boolean createMultiTasks(String plannum, String factory, int facInt,
			float ctrlqty, float ctrlwt) {
		char isNew = '1';
		float workflowqty = 0.0f;
		float workflowwt = 0.0f;
		int linenum = 1;
		String workflow = "QD";
		String plannumf = plannum + "-" + facInt + "1";
		ERPPlanCtrl erp = new ERPPlanCtrl(plannumf, factory, workflow, plannum,
				linenum, ctrlqty, ctrlwt, workflowqty, workflowwt, isNew);
		RWServiceLocal rws = rwHelper.getRWServiceLocal();
		try {
			rws.createERPPlanCtrl(erp);
		} catch (RWException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}



	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		RWServiceLocal rws = rwHelper.getRWServiceLocal();
		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();
		if (action.equals("list")) {
			String date = request.getParameter("date");
			if (date == null)
				date = tools.dateToString(Calendar.getInstance().getTime());
			try {

				List ret = rws
						.findERPFactory(" where ctrlwt>0 and workflow='QD' and ctrldate<'"
								+ date + "' and ctrldatet>'" + date + "'");
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.lang.Float.class,
						new FloatJsonValueProcessor());
				System.out.println("ret.size:"+ret.size());
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (Exception e) {

				System.out.println("Exception is found in action==list:" + e.getMessage());
				response.getWriter().print("{success:false, data:'更新失败!'}");
			}

		} else if (action.equals("detail")) {
			try {
				String ssign = (String) sess.getAttribute("ssign");
				String spec = (String) sess.getAttribute("spec");
				String plate = (String) sess.getAttribute("plate");
				String plannum = (String) sess.getAttribute("plannum");
				String zhenpian = (String) sess.getAttribute("zhenpian");

				String specType = parse.parseSpec(spec).sort();
				Date date1 = Calendar.getInstance().getTime();
				float d1 = regulation.getDensity(ssign);
				try {
					Float gross=new Float(0);
					List retList = gss.findSsignDensity(" where ssign='" + ssign + "'");
					if (retList.size() > 0)
						gross = ((SsignDensity) retList.get(0)).getDensity();
					spec m_spec = parse.parseSpec(spec);

					gross = new Float(m_spec.volume() * gross.floatValue() / 1000 / 1000);
					Float qian = gss.getDefaultCheck(" where spec='" + m_spec.sort()
							+ "' and name='" + GSConstants.DEFUALT_CHECK_QIANDAO_YIELD
							+ "'", spec);
					if (qian.floatValue() > 0)
						gross = new Float(gross.floatValue() / qian.floatValue());
				
				int month1 = tcdate.getMonth(date1);
				int year1 = tcdate.getYear(date1);
				int scheme = 1;
				Product p = new Product(ssign, spec, plate + "_" + plannum
						+ "_" + gross + "_" + zhenpian, month1, year1, 0,
						specType, scheme);
				List ret = new ArrayList();
				ret.add(p);
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
				} catch (GSException gse) {
					System.out.println("getGrossWeight error :" + gse.getMessage());
					response.getWriter().print("{success:false}");
				}
			} catch (Exception e) {

				System.out.println("Exception is found in action==detail:" + e.getMessage());
				response.getWriter().print("{success:false}");
			}

		} else if (action.equals("solo")) {
			// 只安排到一个分厂进行生产
			try {
				String ssign = (String) sess.getAttribute("ssign");
				String spec = (String) sess.getAttribute("spec");
				String plate = (String) sess.getAttribute("plate");
				String zhenpian = (String) sess.getAttribute("zhenpian");
				String plannum = (String) sess.getAttribute("plannum");
				String factory = (String) request.getParameter("factory");
				String facInt = (String) request.getParameter("facInt");

				String plannumf = plannum + "-" + Integer.parseInt(facInt)
						+ "1";
				String workflow = "QD";
				char isNew = '1';
				float workflowqty = 0.0f;
				float workflowwt = 0.0f;
				int linenum = 1;
				float ctrlqty = Float.parseFloat(zhenpian);
				System.out.println("request:"
						+ request.getParameter("loadAfter").toString());
				float ctrlwt = Float.parseFloat(request
						.getParameter("loadAfter"));

				ERPPlanCtrl erp = new ERPPlanCtrl(plannumf, factory, workflow,
						plannum, linenum, ctrlqty, ctrlwt, workflowqty,
						workflowwt, isNew);
				rws.createERPPlanCtrl(erp);
			} catch (RWException e) {
				System.out.println("create_RWException:" + e.getMessage());
				response.getWriter().print("{success:false}");

			} catch (Exception e) {
				System.out.println("exception found:" + e.getMessage());
				response.getWriter().print("{success:false}");
			}
		} else if (action.equals("getDetailByFac")) {
			String factory = request.getParameter("factory");
			String bef = (String) sess.getAttribute("factory");

			String start = request.getParameter("start");
			if (start == null)
				start = "0";
			String limit = request.getParameter("limit");
			if (limit == null)
				limit = "10";

			String date = tools.dateToString(Calendar.getInstance().getTime());
			String whereStr = " where ctrlwt>0 and workflow='QD' and ctrldate<'"
					+ date + "' and ctrldatet>'" + date + "' and factory='"+factory+"'";
			try {
				List subList = new ArrayList();
				List ret = new ArrayList();
				if (bef != null && bef.equals(factory)) {
					ret = (List) sess.getAttribute("factoryList");
				} else
					{
						ret = rws.findERPTaskFromPlan(whereStr);
						sess.removeAttribute("factoryList");
						sess.setAttribute("factoryList", ret);
						sess.removeAttribute("factory");
						sess.setAttribute("factory", factory);
					}
				if (ret.size() < (Integer.parseInt(start) + Integer
						.parseInt(limit))) 
					subList=ret.subList(Integer.parseInt(start), ret.size());
				
				else
					subList=ret.subList(Integer.parseInt(start), Integer.parseInt(limit));
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(subList, cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (RWException e) {
				System.out.println("create_RWException:" + e.getMessage());
				response.getWriter().print("{success:false}");

			} catch (Exception e) {
				System.out.println("exception found:" + e.getMessage());
				response.getWriter().print("{success:false, data:'更新失败!'}");
			}
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
